<?php

namespace app\miniprogram\task;

use app\common\controller\Wechat;
use app\system\model\SystemUser as UserModel;
use app\common\service\WechatUser;
/**
 * 日志管理控制器
 * @package app\system\admin
 */
class AuthLogin extends Wechat{

    protected  $loginUser = '';//登录用户
    protected  $adminId = '';    /* adminid */

    public function initialize(){
        parent::initialize();
        /* 获取header auth tooken */
        $session_key = $this->get_auth_headers('authSession');
        $session_key= empty($session_key) ? $this->param('authSession','') : $session_key;
        if (!empty($session_key)) {
            $user_data=cache(MINI_SESSION.$session_key);
            if(!empty($user_data)){
                $this->adminId = $user_data['admin_id'];
                $this->loginUser=$user_data;
            }
        }
        header("Content-Type: application/json;charset=utf-8");
    }

    public function autoLogin(){
        $iv = $this->param('iv');
        $encryptedData = $this->param('encryptedData');
        $code=$this->param('code');
        $wechatOauth = \We::WeMiniCrypt(config('wechat.'));
        if(isset($code)){
           try {
               if(empty( $iv) || empty($encryptedData)){ //无用户信息授权
                   $wechatdata=$wechatOauth->session($code);
                   if (isset($wechatdata['errcode'])) {
                       $this->return_json('401',$wechatdata['errmsg']);
                   }
                   $weixin_unionid=$wechatdata['openid'];
                   $userInfo = (new WechatUser())->getInfoByUnionid($weixin_unionid);
                   if ($userInfo) {
                       $userInfo['realname'] = db('system_user')->where('id', $userInfo['admin_id'])->value('nick', '');
                       $session_key=$this->setSessionKey($userInfo);
                       $responseArr['userInfo'] = [
                           'wechat_user_id'=>$userInfo['id'],
                           'admin_id'   => $userInfo['admin_id'],
                           'realname'  => $userInfo['realname']?:'',
                           'nick_name'  => $userInfo['nickname'],
                           'headimgurl' => $userInfo['avatar'],
                       ];
                       $responseArr['authSession']=$session_key;
                       $responseArr['bindStatus']= $userInfo['admin_id'] >0 ? 1 : 0;
                   }else{
                       $session_key=md5($weixin_unionid);
                       $responseArr['userInfo']=[];
                       $responseArr['authSession']=$session_key;
                       $responseArr['bindStatus']=0;
                   }
               }else{ //有用户信息授权
                   $wechatUserData=$wechatOauth->userInfo($code, $iv, $encryptedData);
                   $weixin_unionid=$wechatUserData['openid'];
                   // 创建用户或更新用户
                   $wechatUserInfo = (new WechatUser())->getInfoByUnionid($weixin_unionid, 'id,admin_id');
                   if (!$wechatUserInfo) {
                       $insData = [
                           'weixin_unionid' => $wechatUserData['openid'],
                           'nickname' => $wechatUserData['nickName'],
                           'sex' => $wechatUserData['gender'],
                           'province' => $wechatUserData['province'],
                           'city' => $wechatUserData['city'],
                           'country' => $wechatUserData['country'],
                           'headimgurl' => $wechatUserData['avatarUrl'],
                           'subscribe' => 0,
                           'create_time' => time(),
                           'update_time' => time(),
                       ];
                       $insertid=db('wechat_user')->insertGetId($insData);
                       $wechatUserInfo['admin_id']=0;
                       $wechatUserInfo['id']=$insertid;
                   } else {
                       $upData = [
                           'nickname' => $wechatUserData['nickName'],
                           'sex' => $wechatUserData['gender'],
                           'province' => $wechatUserData['province'],
                           'city' => $wechatUserData['city'],
                           'country' => $wechatUserData['country'],
                           'headimgurl' => $wechatUserData['avatarUrl'],
                           'update_time' => time(),
                       ];
                       db('wechat_user')->where('id', $wechatUserInfo['id'])->update($upData);
                   }
                   $userInfo=db('wechat_user')->where('id', $wechatUserInfo['id'])->findOrEmpty();
                   $userInfo['realname'] = db('system_user')->where('id', $wechatUserInfo['admin_id'])->value('nick', '');
                   $session_key=$this->setSessionKey($userInfo);
                   $responseArr['userInfo'] = [
                       'wechat_user_id'=>$userInfo['id'],
                       'admin_id'   => $userInfo['admin_id'],
                       'realname'  => $userInfo['realname']?:'',
                       'nick_name'  => $userInfo['nickname'],
                       'headimgurl' => $userInfo['avatar'],
                   ];
                   $responseArr['authSession']=$session_key;
                   $responseArr['bindStatus']= $userInfo['admin_id'] >0 ? 1 : 0;
               }
               $this->return_json(200,$responseArr);

            } catch (\Exception $e) {
                $this->return_json(403,$e->getMessage());
            }
        }else{
             $this->return_json(403,'code未传递');
        }
    }

    //保存登录信息
    protected function setSessionKey($userInfo){
        $session_key=md5($userInfo['weixin_unionid']);
        $sessionData  = array(
            'wechat_user_id'=>$userInfo['id'],
            'openid' => $userInfo['weixin_unionid'],
            'admin_id' => $userInfo['admin_id'],
            'nickname'=>$userInfo['nickname'],
            'realname'  => $userInfo['realname'],
        );
        cache(MINI_SESSION.$session_key, $sessionData, 30*86400);
        return $session_key;
    }


    /**
     * 个人中心
     */
    public function loginUser(){

        $user_id = session('app_user_id');
        $user = M('user')->where(array('id' => $user_id))->field('id as user_id,logo,face,weixin_num,weixin_username,realname,username,currency,brokerage,weixin_unionid,weixin_openid,is_elite,integral')->cache(2)->find();
        if ($user) {
            //消息通知数量
            $user['message_count'] = M('message_user')->where(array('recipient_id' => $user_id, 'is_show' => 1, 'is_read' => 0))->count('id');
            $user['face'] = $user['logo'] ?: getUserFace($user['face']);//头像
            $user_group = getUserGroup($user_id); //用户组
            $user['group_name'] = $user_group['group_name'];
            $user['isBind'] = $user['is_elite'] ? 1 : 0; //是否绑定后台帐号
            return jsonReturn(0, $user);
        }else{
            return jsonReturn(10000);
        }
    }

    public function param($args='',$default=''){
        return $this->request->param($args,$default);
    }

    /**
     * return json for data
     * @param   mixed $data   要返回的数据/出错消息
     * @param   int   $code   结果编辑码 ok/ok_online/e_args/e_op_fall/e_deny
     * @return void
     */
    public function return_json($code =200, $data = array()){
        $result['code'] = $code;
        $result['msg'] = $this->result_code_to_name($code);
        if ($code != 200) {
            if (!empty($data) && !is_array($data)) {
                $result['msg'] = $data;
            } elseif (is_array($data)) {
                $result['data'] = $data;
            }
            echo json_encode($result, JSON_UNESCAPED_UNICODE);
            exit;
        }
        if (!empty($data)) {
            $result['data'] = $data;
        }
        echo json_encode($result, JSON_UNESCAPED_UNICODE);
        exit;
    }

    /**
     * code转中文
     * @param   int   $code   结果编辑码
     * @return $string
     */
    protected function result_code_to_name($code){
        switch ($code) {
            case 200:
                $r = '请求成功';
                break;
            case 'ok_online':
                $r = '操作成功,请等待...';
                break;
            case 'e_args':
                $r = '参数出错';
                break;
            case 'e_op_fall':
                $r = '操作失败';
                break;
            case 'e_deny':
                $r = '拒绝访问';
                break;
            default:
                $r = '请求失败';
                break;
        }
        return $r;
    }

    /**
     * @brief get http headers
     * @return
     */
    function get_auth_headers($header_key = null){
        if (function_exists('apache_request_headers')) {
            /* Authorization: header */
            $headers = apache_request_headers();
            $out = array();
            foreach ($headers AS $key => $value) {
                $key = str_replace(" ", "-", ucwords(strtolower(str_replace("-", " ", $key))));
                $out[$key] = $value;
            }
        } else {
            $out = array();
            if (isset($_SERVER['CONTENT_TYPE'])) {
                $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
            }
            if (isset($_ENV['CONTENT_TYPE'])) {
                $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
            }
            foreach ($_SERVER as $key => $value) {
                if (substr($key, 0, 5) == "HTTP_") {
                    $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
                    $out[$key] = $value;
                }
            }
        }
        if ($header_key != null) {
            $header_key = ucfirst(strtolower($header_key));
            if (isset($out[$header_key])) {
                return $out[$header_key];
            } else {
                return false;
            }
        }
        return $out;
    }


}
